package com.ruoyi.find.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.find.domain.SysUser;
import com.ruoyi.find.mapper.SysUserMapper;
import com.ruoyi.find.service.SysUserService;
import com.ruoyi.find.vo.LoginVo;
import com.ruoyi.system.api.model.LoginUser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private TokenService tokenService;

    @Override
    public R getphonecode(LoginVo loginVo) {
        SysUser user = userMapper.selectByPhone(loginVo.getPhoneNumber());
        if(user == null){
            return R.fail("用户不存在");
        }
        String phonecode = RandomUtil.randomNumbers(4);
        stringRedisTemplate.opsForValue().set(loginVo.getPhoneNumber(),phonecode,60, TimeUnit.MINUTES);
        return R.ok(phonecode);
    }

    @Override
    public R getphonelogin(LoginVo loginVo) {
        // 1. 查询用户
        SysUser user = userMapper.selectByPhone(loginVo.getPhoneNumber());
        if (user == null) {
            return R.fail("用户不存在");
        }

        // 2. 验证验证码
        String phoneCodeRedis = stringRedisTemplate.opsForValue().get(loginVo.getPhoneNumber());
        if (phoneCodeRedis == null) {
            return R.fail("验证码失效");
        }
        if (!phoneCodeRedis.equals(loginVo.getPhoneCode())) {
            return R.fail("验证码错误");
        }

        // 3. 将 com.ruoyi.find.domain.SysUser 转换为 com.ruoyi.system.api.domain.SysUser
        com.ruoyi.system.api.domain.SysUser apiSysUser = convertToApiSysUser(user);

        // 4. 创建 LoginUser 对象
        LoginUser loginUser = new LoginUser();
        loginUser.setSysUser(apiSysUser); // 确保类型正确

        // 5. 使用 tokenService 生成 token
        Map<String, Object> tokenInfo = null;
        try {
            tokenInfo = tokenService.createToken(loginUser);
            if (tokenInfo == null || !tokenInfo.containsKey("access_token")) {
                log.error("token生成失败，tokenInfo: {}", tokenInfo);
                return R.fail("登录失败，请重试");
            }

            // 提取 access_token
            String accessToken = (String) tokenInfo.get("access_token");
            log.info("成功生成 access_token: {}", accessToken);

            // 设置 token 到 user 对象
            user.setPassword(null); // 清除密码
            user.setToken(accessToken);   // 设置 token

            return R.ok(user);
        } catch (Exception e) {
            log.error("token生成过程中发生异常，loginUser: {}, error: {}", loginUser, e.getMessage(), e);
            return R.fail("登录失败，请重试");
        }
    }

    /**
     * 将 com.ruoyi.find.domain.SysUser 转换为 com.ruoyi.system.api.domain.SysUser
     */
    private com.ruoyi.system.api.domain.SysUser convertToApiSysUser(SysUser findSysUser) {
        com.ruoyi.system.api.domain.SysUser apiUser = new com.ruoyi.system.api.domain.SysUser();
        apiUser.setUserId(findSysUser.getUserId());
        apiUser.setDeptId(findSysUser.getDeptId());
        apiUser.setUserName(findSysUser.getUserName());
        apiUser.setNickName(findSysUser.getNickName());
        apiUser.setEmail(findSysUser.getEmail());
        apiUser.setPhonenumber(findSysUser.getPhonenumber());
        apiUser.setSex(findSysUser.getSex());
        apiUser.setAvatar(findSysUser.getAvatar());
        apiUser.setPassword(findSysUser.getPassword());
        apiUser.setStatus(findSysUser.getStatus());
        apiUser.setDelFlag(findSysUser.getDelFlag());
        apiUser.setLoginIp(findSysUser.getLoginIp());
        apiUser.setLoginDate(findSysUser.getLoginDate());
        apiUser.setPwdUpdateDate(findSysUser.getPwdUpdateDate());
        return apiUser;
    }

    @Override
    public R getadduser(SysUser sysUser) {
        userMapper.insert(sysUser);
        return null;
    }
}
